import React, { useState, useEffect, useRef } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faSearch, faTimes } from '@fortawesome/free-solid-svg-icons'
import PropTypes from 'prop-types'
import useKeyPress from '../hooks/userKeyPress'

const FileSearch = ({ title, onFileSearch, activeSearch }) => {
  const [inputActive, setInputActive] = useState(false)
  const [value, setValue] = useState('')
  const enterPressed = useKeyPress(13)
  const escPressed = useKeyPress(27)

  const closeSearch = () => {
    setInputActive(false)
    setValue('')
    onFileSearch('')
  }

  useEffect(() => {
    if(activeSearch){
      setInputActive(true)
    }
  }, [activeSearch])

  useEffect(() => {
    if(enterPressed && inputActive){
      onFileSearch(value)
    }
    if(escPressed && inputActive){
      closeSearch()
    }
  })
  let node = useRef(null)
  useEffect(() => {
    if (inputActive) {
      node.current.focus()
    }
  }, [inputActive])
  return (
    <div className="alert mb-0 alert-primary d-flex justify-content-between align-items-center">
      {
        !inputActive &&
        <>
          <span className="title">{title}</span>
          <button
            type="button"
            onClick={() => { setInputActive(true) }}
            className="icon-button">
            <FontAwesomeIcon
              title="搜索"
              size="lg"
              icon={faSearch} />
          </button>
        </>
      }
      {
        inputActive &&
        <>
          <input
            onChange={(e) => { setValue(e.target.value) }}
            className="form-control"
            ref={node}
            value={value} />
          <button
            type="button"
            onClick={closeSearch}
            className="icon-button">
            <FontAwesomeIcon
              title="关闭"
              size="lg"
              icon={faTimes} />
          </button>
        </>
      }
    </div>
  )
}

FileSearch.propTypes = {
  title: PropTypes.string,
  onFileSearch: PropTypes.func.isRequired
}

FileSearch.defaultProps = {
  title: '我的云文档'
}
export default FileSearch